package cn.yuhao.party.file.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

import sun.misc.BASE64Encoder;
import cn.itcast.servlet.BaseServlet;
import cn.yuhao.party.file.domain.FileDomain;
import cn.yuhao.party.file.service.FileService;
import cn.yuhao.party.pager.PageBean;
public class DownloadServlet extends BaseServlet {
	private FileService fs=new FileService();
	public String delete(HttpServletRequest request, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String filename=request.getParameter("file");
		try {
			fs.delete(filename);
			
		} catch (SQLException e) {
			request.setAttribute("msg", "文件删除失败");
			System.out.println("文件删除失败");
			throw new RuntimeException(e);
		}
		request.setAttribute("msg", "删除文件成功");
		return "f:/jsps/login/welcome/success.jsp";
	}
	public String AdminFindAll(HttpServletRequest request, HttpServletResponse resp)
			throws ServletException, IOException {
		int pc=getPc(request);
		String url=getUrl(request);
		PageBean<FileDomain> pb= (PageBean<FileDomain>) fs.findAll(pc);
		pb.setUrl(url);
		request.setAttribute("pb", pb);
		System.out.println(pb.getBeanList());
		return "f:/jsps/login/welcome/deletefile.jsp";
	}
	public String findAll(HttpServletRequest request, HttpServletResponse resp)
			throws ServletException, IOException {
		int pc=getPc(request);
		String url=getUrl(request);
		PageBean<FileDomain> pb= (PageBean<FileDomain>) fs.findAll(pc);
		pb.setUrl(url);
		request.setAttribute("pb", pb);
		System.out.println(pb.getBeanList());
		return "f:/jsps/pingtai/download.jsp";
	}
	public void download(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		/*
		 * 两个头一个流
		 * 1. Content-Type
		 * 2. Content-Disposition
		 * 3. 流：下载文件的数据
		 */
		//String filename = "F:/MS-DOS命令大全.doc";
		String name=req.getParameter("file");
		// 为了使下载框中显示中文文件名称不出乱码！
		String filename=this.getServletContext().getRealPath("/WEB-INF/files/")+"//"+name;
//		String framename = new String("流光%飞舞.mp3".getBytes("GBK"), "ISO-8859-1");
		String framename = filenameEncoding(name, req);
		
		String contentType = this.getServletContext()
				.getMimeType(filename);//通过文件名称获取MIME类型
		String contentDisposition = "attachment;filename=" + framename;
		// 一个流
		FileInputStream input = new FileInputStream(filename);
		
		//设置头
		resp.setHeader("Content-Type", contentType);
		resp.setHeader("Content-Disposition", contentDisposition);
		
		// 获取绑定了响应端的流
		ServletOutputStream output = resp.getOutputStream();
		
		IOUtils.copy(input, output);//把输入流中的数据写入到输出流中。
		
		input.close();
	}
	
	// 用来对下载的文件名称进行编码的！
	public static String filenameEncoding(String filename, HttpServletRequest request) throws IOException {
		String agent = request.getHeader("User-Agent"); //获取浏览器
		if (agent.contains("Firefox")) {
			BASE64Encoder base64Encoder = new BASE64Encoder();
			filename = "=?utf-8?B?"
					+ base64Encoder.encode(filename.getBytes("utf-8"))
					+ "?=";
		} else if(agent.contains("MSIE")) {
			filename = URLEncoder.encode(filename, "utf-8");
		} else {
			filename = URLEncoder.encode(filename, "utf-8");
		}
		return filename;
	}
	private int getPc(HttpServletRequest req) {
		int pc = 1;
		String param = req.getParameter("pc");
		if(param != null && !param.trim().isEmpty()) {
			try {
				pc = Integer.parseInt(param);
			} catch(RuntimeException e) {}
		}
		return pc;
	}
	
	/**
	 * 截取url，页面中的分页导航中需要使用它做为超链接的目标！
	 * @param req
	 * @return
	 */
	/*
	 * http://localhost:8080/goods/BookServlet?methed=findByCategory&cid=xxx&pc=3
	 * /goods/BookServlet + methed=findByCategory&cid=xxx&pc=3
	 */
	private String getUrl(HttpServletRequest req) {
		String url = req.getRequestURI() + "?" + req.getQueryString();
		/*
		 * 如果url中存在pc参数，截取掉，如果不存在那就不用截取。
		 */
		int index = url.lastIndexOf("&pc=");
		if(index != -1) {
			url = url.substring(0, index);
		}
		return url;
	}
}
